<?php

namespace App\Services\Role;

use App\Lib\Util\ErrorCode;
use App\Models\Admin\RoleMenuRightModel;
use App\Models\Admin\RoleModel;

/**
 * Class RoleService
 * @package App\Services\Admin
 */
class RoleService
{

  private $RoleModel;
  private $RoleMenuRightModel;

  public function __construct(RoleModel $RoleModel,RoleMenuRightModel $RoleMenuRightModel)
  {
    $this->RoleModel = $RoleModel;
    $this->RoleMenuRightModel = $RoleMenuRightModel;
  }

  /**
   * 获取角色信息
   * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
   * @throws \Exception
   */
  public function getRoleList()
  {
    $arrRoleInfo = $this->RoleModel::query()->with(
      [
        'routes' => function ($query) {
          $query->select('admin_menu.id','title','hidden','path');
        }
      ]
    )->get();
    if (empty($arrRoleInfo)) {
      throw new \Exception('', ErrorCode::NO_DATA);
    }
    return $arrRoleInfo;
  }

  /**
   * 添加角色信息
   * @param $data
   * @return array
   */
  public function addRole($data)
  {
    $routes = $data['routes'];
    $data =array(
      'name'=>$data['name'],
      'key'=>$data['name'],
      'description'=>$data['description'],
    );
    $role_id = $this->RoleModel::query()->insertGetId($data);
    $data['role_id']=$role_id;

    foreach ($routes as $val){
      $this->RoleMenuRightModel::query()->create(array('menu_id'=>$val,'role_id'=>$role_id))->toArray();
      unset($val);
    }
    return $data;
  }

  /**
   * 更信角色信息
   * @param $data
   * @return int
   */
  public function editRole($data)
  {
    $routes = $data['routes'];
    $update = array();
    $id = $data['id'];
    unset($data['id']);
    if (!empty($data['name'])) {
      $update['name'] = $data['name'];
    }
    if (!empty($data['description'])) {
      $update['description'] = $data['description'];
    }
    //清空历史权限
    $this->RoleMenuRightModel::query()->where('role_id', $id)->delete();
    //插入新权限
    foreach ($routes as $val){
      $this->RoleMenuRightModel::query()->create(array('menu_id'=>$val,'role_id'=>$id))->toArray();
      unset($val);
    }
    return $this->RoleModel::query()->where('id', $id)->update($update);
  }

  /**
   * 删除角色信息
   * @param $id
   * @return mixed
   */
  public function delRole($id)
  {
    $data = array($id);
    $res = $this->RoleModel::query()->whereIn('id', $data)->delete();
    return $res;
  }

}
